<?php

namespace app\common\util\plug;

use app\model\Plugs;
use app\common\util\base\BaseObserver;
use think\Exception;

class PlugCreateLog extends BaseObserver
{
    public function handle()
    {
        $plugInfo = $this->server->getPlugInfo();
        trace($plugInfo);
        $plugs = Plugs::where([
            'name'  =>  $plugInfo['name'],
            'author'  =>  $plugInfo['author']
        ])->find();
        if (!$plugs){
            $plugs = Plugs::create([
                'name'  =>  $plugInfo['name'],
                'author'  =>  $plugInfo['author'],
                'version'=> $plugInfo['version'] ?? '',
                'introduction'  =>  $plugInfo['introduction'],
                'status'  =>  1,
            ]);
        }else{
            if ($plugs->version != $plugInfo['version']) {
                list($newPlugBigVersion, $newPlugMidVersion, $newPlugSmlVersion) = explode('.', $plugInfo['version']);
                list($oldPlugBigVersion, $oldPlugMidVersion, $oldPlugSmlVersion) = explode('.', $plugs->version);
                if ($newPlugBigVersion <= $oldPlugBigVersion && $newPlugMidVersion <= $oldPlugMidVersion && $newPlugSmlVersion < $oldPlugSmlVersion) {
                    throw new Exception('无法回退版本');
                }
            }
        }
        trace('插件数据已创建...');
        return $plugs;
    }
}